package com.push_label.controller;


import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.push_label.bean.sys_user.LoginResult;
import com.push_label.bean.sys_user.LoginDto;
import com.push_label.bean.sys_user.SysUserInfo;
import com.push_label.common.Result;
import com.push_label.server.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/auth")
@Slf4j
public class LoginController {

    @Resource
    public UserService userService;

    @PostMapping("/login")
    public Result<LoginResult> login(@RequestBody LoginDto loginResult) {
        log.info("login");

        if (StrUtil.isEmpty(loginResult.getUsername()) || StrUtil.isEmpty(loginResult.getPassword())) {
            return Result.fail("用户名或密码不能为空");
        }

        SysUserInfo sysUserInfo = userService.selectUserInfoByUsername(loginResult.getUsername());
        if (sysUserInfo == null) {
            return Result.fail("用户不存在");
        }

        if (!sysUserInfo.getUser_password().equals(loginResult.getPassword())) {
            return Result.fail("密码错误");
        }

        StpUtil.login(sysUserInfo.getUser_id());

        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        LoginResult login_result = new LoginResult();
        login_result.setUser_id(sysUserInfo.getUser_id());
        login_result.setUser_name(sysUserInfo.getUser_name());
        login_result.setUser_code(sysUserInfo.getUser_code());
        login_result.setToken(tokenInfo.getTokenValue());

        return Result.success(login_result);
    }


    @GetMapping("/checkLogin")
    public Result<Void> checkLogin(){
        System.out.println("检查用户信息");
        if (!StpUtil.isLogin()) {
            return Result.fail("未登录");
        }
        return Result.success();
    }


    @PostMapping("/logout")
    public Result<Void> logout(){
        StpUtil.logout();
        return Result.success();
    }




}
